package cn.tpshion.task.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

public class TaskChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final HeartbeatHandler heartbeatHandler;

    private final ClientHandler clientHandler;

    public TaskChannelInitializer(HeartbeatHandler heartbeatHandler, ClientHandler clientHandler) {
        this.heartbeatHandler = heartbeatHandler;
        this.clientHandler = clientHandler;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        // 添加粘包/拆包处理器
        pipeline.addLast(new LengthFieldBasedFrameDecoder(
            Integer.MAX_VALUE,
            0,
            4,
            0,
            4));
        pipeline.addLast(new LengthFieldPrepender(4));

        // 字符串编解码器
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

        pipeline.addLast(new IdleStateHandler(0, 5, 0));
        pipeline.addLast(heartbeatHandler);

        // 业务处理器
        pipeline.addLast(clientHandler);

    }
}
